package com.hevery.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hevery.security.browser.support.SimpleResponse;
import com.hevery.security.core.properties.LoginType;
import com.hevery.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: zhy
 * @description:
 * @date: created on 2017/10/25
 * @modified by:
 */
//https://www.oschina.net/p/ybg-spring-fast
@Component("CustomAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 如果配置是登录后返回JOSN，则登录认证失败后会返回一个JSON格式的信息；否则会调用父类的放回，返回一个错误的登录页面(SpringSecurity默认的处理方式)
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        logger.info("登录失败");
        //默认情况下，登录成功状态码返回200；但是现在要重新设置一下，登录失败，返回500
        if(LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");

            //不把整个异常(包括堆栈信息)都返回去，只返回错误信息
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(e.getMessage())));
        }else {
            super.onAuthenticationFailure(request,response,e);
        }

    }
}
